<?php
declare(strict_types=1);
namespace App\Controller\Api;

use App\Exception\BusinessException;
use App\Exception\ErrorMessageException;
use App\Model\BilibiliVideo;
use App\Model\BilibiliVideoPage;
use App\Request\DownloadVideoRequest;
use App\Request\getBilibiliRequest;
use App\Services\httpRequestService;

use App\Services\QueueManageService;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Request;
use Hyperf\Validation\ValidationRuleParser;
use Xxh\FileStore\Service\FileStoreAbstract;

/**
 * @AutoController()
 */
class BilibiliController extends ApiController
{

    /**
     * @Inject
     * @var httpRequestService
     */
    private $httpRequest;


    /**
     * 文件管理
     * @Inject
     * @var FileStoreAbstract
     */
    private $file;

    /**
     * @Inject
     * @var QueueManageService
     */
    private $queueManageService;


    const BILIBILI_VIDEO_API = 'https://api.bilibili.com/x/web-interface/view?bvid=';
   // const BILIBILI_VIDEO_API = 'https://api.bilibili.com/x/player/pagelist?bvid=';
    public function getVideoInfo(GetBilibiliRequest $request)
    {
        $aid = $this->getAid( $request->input('href'));

        if (! $aid)
        throw new ErrorMessageException('未匹配到av号　请手动输入av号试试吧');

        $content = $this->httpRequest->httpGet(self::BILIBILI_VIDEO_API.$aid)->getBody()->getContents();
        $content = json_decode($content);

        if( $content->code != 0)
        throw new ErrorMessageException('获取视频信息失败');

        $content->data->aid = $aid;

        $exists = BilibiliVideo::Where('aid',$content->data->aid)->first()  == null ? false : true;

         if(! $exists){
                $video = BilibiliVideo::firstOrCreate([
                    'aid' => $content->data->aid,
                    'title' => $content->data->title,
                    'desc' => $content->data->desc,
                    'pic' => $content->data->pic
                ]);
                $this->updatePic($video,$content->data->pic);
       }


        $this->createPages($content->data->pages,$content->data->aid);
         return $this->ok(
            $content->data
        );
    }


    protected function updatePic($video,$pic)
    {
        $saveFilePath = 'bilibili/'.$video->aid.'.jpg';


        if( $this->file->fileExists($saveFilePath)) //文件存在
        return true;

        $content = file_get_contents($pic);
        $path = $this->file->put($saveFilePath,$content);

        $video->pic = $this->file->url($path);
        return $video->save();
    }

    protected function createPages($pages,$aid)
    {

        foreach ($pages as $page){

           if( BilibiliVideoPage::Where('cid',$page->cid)->first() == null){
                BilibiliVideoPage::Create([
                   'cid' => $page->cid,
                    'part' => $page->part,
                    'duration' => $page->duration,
                    'aid' => $aid
                ]);

           }
        }
    }

    protected function getAid($href)
    {

        $href = parse_url($href);
        $paths = $href['path'];
        $path_arr = explode('/',$paths);
        $bvid = $path_arr[ count($path_arr)-1];

        return $bvid;
    }


    /*
     *@下载bilibili视频
     */
    public function downloadVideo(DownloadVideoRequest $request)
    {
        $pages = is_array($request->input('pages')) ? $request->input('pages')
            : json_decode($request->input('pages'));

        foreach ($pages as $page){
            $page->aid = $request->input('aid');
            $this->queueManageService->pushBilibiliVideoDownload($page);
        }
        return $this->ok('已加入队列下载');
    }





    public function videoList()
    {

        return $this->ok(
            BilibiliVideo::WithCount('pages')->paginate(10)
        );
    }


    public function getVideoDetail(Request $request)
    {
        return $this->ok(
          BilibiliVideo::With('pages')->find($request->input('id'))
        );
    }

}

